//
//  FinishedOrder.m
//  RRQS
//
//  Created by kuyuZJ on 16/8/17.
//
//

#import "FinishedOrder.h"
#import "FinishedOrderCell.h"
#import "FinishedOrderHeader.h"
#import "Pager.h"
#import "MFinishedTask.h"
#import "FinishedTaskDetail.h"
@interface FinishedOrder ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong) UILabel* topView;


@property(nonatomic,strong) UICollectionView* collectionView;
@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSMutableArray* arrayData;
@property(nonatomic,strong) Pager* page;

@end

@implementation FinishedOrder

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"已完成的任务";
    self.cellIdentifier =  @"FinishedOrderCell";
    self.headerIdentifier =  @"FinishedOrderHeader";
    [self layoutUI];
    [self layoutConstraints];
    [self refreshDataSource];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


#pragma mark =====================================================  user interface layout
-(void)layoutUI{
    [self.view addSubview:self.topView];
    
    [self.view addSubview:self.collectionView];
}

-(void)layoutConstraints{
    NSArray* formats = @[ @"H:|-0-[topView]-0-|", @"V:[top][topView(==45)]",
                          @"H:|-0-[collectionView]-0-|", @"V:[topView][collectionView][bottomView]"
                          ];
    NSDictionary* metorics = nil;
    NSDictionary* views = @{ @"top":self.topLayoutGuide, @"topView":self.topView, @"collectionView":self.collectionView, @"bottomView":self.bottomLayoutGuide};
    
    for (NSString* format in formats) {
        NSArray* constraints =[NSLayoutConstraint constraintsWithVisualFormat:format options:0 metrics:metorics views:views];
        [self.view addConstraints:constraints];
    }
}

#pragma mark =====================================================  DataSource
-(void)queryData{
    AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
    NSDictionary* arg = @{@"ince":@"get_overorder_list",@"emp_id":self.Identity.userInfo.userID,@"page":[WMHelper integerConvertToString:self.page.pageIndex]};
    [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [WMHelper outPutJsonString:responseObject];
        NSInteger flag = [[responseObject objectForKey:@"status"]integerValue];
        if(self.page.pageIndex == 1){
            [self.arrayData removeAllObjects];
        }
        NSInteger totalCount = 0;
        NSInteger currentCount = 0;
        if(flag == 1){
            totalCount = [[responseObject objectForKey: @"total"] integerValue];
            NSArray* array = [responseObject objectForKey:@"list"];
            if(![WMHelper isNULLOrnil:array]){
                currentCount = array.count;
                [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    MFinishedTask* item = [[MFinishedTask alloc]initWithItem:obj];
                    self.page.recordCount+= [item.count integerValue];
                    [self.arrayData addObject:item];
                }];
            }
            [self loadDataTitel:[responseObject objectForKey:@"total"]];
        }else{
            [self alertHUD:[responseObject objectForKey:@"fail"]];
        }
        [self.collectionView reloadData];
        if(self.page.pageIndex == 1 ){
            [self.collectionView.mj_header endRefreshing];
        }else if (self.page.pageIndex>1){
            [self.collectionView.mj_footer endRefreshing];
        }
        if(self.page.recordCount >= totalCount){
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        [self alertHUD:@"网络异常"];
        [self.collectionView.mj_header endRefreshing];
    }];
}

-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page.pageIndex = 1;
        weakSelf.page.recordCount = 0;
        weakSelf.page.groupSection = 0;
        [weakSelf queryData];
    }];
    self.collectionView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.page.pageIndex ++;
        [weakSelf queryData];
    }];    
    [self.collectionView.mj_header beginRefreshing];
}


#pragma mark =====================================================  UICollectionView 协议实现
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.arrayData.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    MFinishedTask* empty = self.arrayData[section];
    return empty.arrayOrder.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    FinishedOrderCell *cell = (FinishedOrderCell*)[collectionView dequeueReusableCellWithReuseIdentifier:self.cellIdentifier forIndexPath:indexPath];
    MFinishedTask* empty = self.arrayData[indexPath.section];
    cell.entity = empty.arrayOrder[indexPath.row];
    cell.arrayOrder = empty.arrayOrder;
    cell.tag = indexPath.row;
    UITapGestureRecognizer *tapgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureTouch:)];
    [cell addGestureRecognizer:tapgr];
    return cell;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if([kind isEqualToString:UICollectionElementKindSectionHeader]){
        UICollectionReusableView  *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:self.headerIdentifier forIndexPath:indexPath];
        FinishedOrderHeader* emptyHeader = (FinishedOrderHeader*)reusableView;
        emptyHeader.entity = self.arrayData[indexPath.section];
        return reusableView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    MFinishedTask* empty = self.arrayData[indexPath.section];
    __block CGFloat height = 0.f;
    height+=100.f;
    MOrder* item = empty.arrayOrder[indexPath.row];
    [item.arrayStore enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        height+=35.f;
    }];
    return CGSizeMake(SCREEN_WIDTH, height);
}


-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(SCREEN_WIDTH, 35);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 1.f; /// 行与行之间的间隔距离
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.f; //相邻两个 item 间距
}

#pragma mark =====================================================  SEL
-(IBAction)gestureTouch:(UIGestureRecognizer*)sender{
    FinishedOrderCell* cell = (FinishedOrderCell*)sender.view;
    FinishedTaskDetail* controller = [[FinishedTaskDetail alloc]init];
    controller.entity = cell.entity;
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark =====================================================  private method
-(void)loadDataTitel:(NSString*)title{
    if(title){
        title = [NSString stringWithFormat:@"%@单",title];
        NSString* str = [NSString stringWithFormat:@"累计单量 : %@",title];
        NSMutableAttributedString* attributeStr = [[NSMutableAttributedString alloc]initWithString:str];
        [attributeStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:24.f],NSForegroundColorAttributeName:[UIColor colorWithRed:248/255.f green:159/255.f blue:39/255.f alpha:1.0]} range:[str rangeOfString:title]];
        self.topView.attributedText = attributeStr;
    }else{
        
    }
}

#pragma mark =====================================================  property package
-(UILabel *)topView{
    if(!_topView){
        _topView = [[UILabel alloc]init];
        _topView.textAlignment = NSTextAlignmentCenter;
        _topView.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _topView;
}

-(UICollectionView *)collectionView{
    if(!_collectionView){
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:[[UICollectionViewFlowLayout alloc]init]];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [self.collectionView registerClass:[FinishedOrderCell class] forCellWithReuseIdentifier:self.cellIdentifier];
        [self.collectionView registerClass:[FinishedOrderHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:self.headerIdentifier];
        _collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _collectionView;
}

-(NSMutableArray *)arrayData{
    if(!_arrayData){
        _arrayData = [[NSMutableArray alloc]init];
    }
    return _arrayData;
}

-(Pager *)page{
    if(!_page){
        _page = [[Pager alloc]init];
        _page.pageIndex = 1;
    }
    return _page;
}

@end
